import { ipcMain, Notification } from 'electron'
import schedule from 'node-schedule'
import type { RemindType } from '../../src/api/interface'
import Log from '../log'

const jobMap = new Map<number, schedule.Job>()

// 提醒
const remind = (data: RemindType) => {
  if (Notification.isSupported()) {
    const notification = new Notification({
      title: data.title,
      timeoutType: 'never'
    })
    Log.info(`执行任务: ${data.title}，时间：${new Date().toLocaleString()}`)
    notification.show()
  }
}

// 添加任务
ipcMain.on('schedule', (_, data: RemindType) => {
  jobMap.set(
    data.id,
    schedule.scheduleJob(data.cron, () => {
      remind(data)
    })
  )
})

// 批量添加任务
ipcMain.on('batch-schedule', (_, data: RemindType[]) => {
  data.forEach((item) => {
    jobMap.set(
      item.id,
      schedule.scheduleJob(item.cron, () => {
        remind(item)
      })
    )
  })
})

// 删除任务
ipcMain.on('delete-schedule', (_, id: number) => {
  const job = jobMap.get(id)
  if (job) {
    job.cancel()
    jobMap.delete(id)
  }
})

// 获取下次提醒时间
ipcMain.handle('get-next-remind-time', (_, id: number) => {
  return new Promise((resolve, reject) => {
    const job = jobMap.get(id)
    if (job) {
      resolve(job.nextInvocation())
    } else {
      reject(new Error('任务不存在'))
    }
  })
})
